package com.xge.business

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.google.gson.Gson
import com.xge.business.bean.LunarBean
import com.xge.business.databinding.ActivityLunarBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.net.URLEncoder
import java.time.LocalDate
import java.time.format.TextStyle
import java.util.Locale

class LunarActivity : AppCompatActivity() {

    private lateinit var binding: ActivityLunarBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityLunarBinding.inflate(layoutInflater)
        setContentView(binding.root)


        val today = LocalDate.now()
        val year = today.year
        val month = today.monthValue
        val day = today.dayOfMonth
        val dayOfWeek = today.dayOfWeek.getDisplayName(TextStyle.FULL, Locale.CHINA)
        binding.tvNowDate.text = "${year}年${month}月${day}日 $dayOfWeek"

        lifecycleScope.launch {
            val url = "https://apis.tianapi.com/lunar/index"
            val params = mapOf(
                "key" to "8112b172e5582ef9a754a0ee751404ba",
            )
            val json = makeGetRequestWithParams(url, params)
            val lunarBean = Gson().fromJson(json, LunarBean::class.java)
            if (lunarBean.code == 200) {
                val bean = lunarBean.result
                binding.tvYi.text = bean?.fitness?.toVertical()
                binding.tvJi.text = bean?.taboo?.toVertical()
                binding.tvDay.text = LocalDate.now().dayOfMonth.toString()
                binding.tvLunarDay.text = "${bean?.lubarmonth}${bean?.lunarday}"
                binding.tvLunarDate.text =
                    "${bean?.tiangandizhiyear}${bean?.shengxiao}年 ${bean?.tiangandizhimonth}月 ${bean?.tiangandizhiday}日"
                binding.tvTaiShen.text = "${bean?.taishen}"
                binding.tvWuXing.text =
                    "${bean?.wuxingjiazi}${bean?.wuxingnamonth}${bean?.wuxingnayear}"
                binding.tvXingXiu.text = "${bean?.xingsu}"
                binding.tvChongSha.text = "${bean?.chongsha}"
                binding.tvPengZu.text = "${bean?.pengzu}"
            } else {
                Toast.makeText(this@LunarActivity, "网络请求失败", Toast.LENGTH_SHORT).show()
            }
        }

    }

    private suspend fun makeGetRequestWithParams(
        url: String, params: Map<String, String>
    ): String? {
        return withContext(Dispatchers.IO) {
            try {
                // 拼接参数
                val fullUrl = buildUrlWithParams(url, params)

                val client = OkHttpClient()

                val request = Request.Builder().url(fullUrl).build()

                val response = client.newCall(request).execute()
                response.body?.string()
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
        }
    }

    private fun buildUrlWithParams(baseUrl: String, params: Map<String, String>): String {
        val paramString = params.map {
            "${URLEncoder.encode(it.key, "UTF-8")}=${URLEncoder.encode(it.value, "UTF-8")}"
        }.joinToString("&")
        return "$baseUrl?$paramString"
    }

    fun String.toVertical(): String = this.replace(".", " ").toCharArray().joinToString("\n")

    companion object{
        fun start(context: Context){
            context.startActivity(Intent(context, LunarActivity::class.java))
        }
    }
}